package com.xbq.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Main {

	public static void main(String[] args) {

		// 定义线程池
		ExecutorService service = Executors.newCachedThreadPool();
		
		// 只能有10个线程同时访问，用来模拟并发
		final Semaphore semaphore = new Semaphore(10);
		
		// 模拟10个客户端访问 
		for (int i = 0; i < 10; i++) {
			Runnable runnable = new Runnable() {
				String lockKey = "XBQ";
				String lockValue = "TestValue";
				@Override
				public void run() {
					try {
						// 获取许可 
						semaphore.acquire();
						
						if(RedisLock.Lock(lockKey, lockValue, 10, 60)){
							// 业务代码
		                    Thread.sleep(3000);
						}
						// 释放锁
						RedisLock.UnLock(lockKey);
	                    
	                    // 访问完后，释放 ，如果屏蔽下面的语句，则在控制台只能打印5条记录，之后线程一直阻塞
						semaphore.release();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			// 执行线程
			service.execute(runnable);
		}
		// 退出线程池 
		service.shutdown();
	}
}
